<template>
  <div class="product-management">
    <!-- 筛选栏 -->
    <el-form :inline="true" :model="filters" class="filter-form">
      <el-form-item label="商品名称">
        <el-input v-model="filters.keyword" placeholder="请输入商品名称" clearable />
      </el-form-item>
      <el-form-item label="商品分类">
        <el-select v-model="filters.category" placeholder="全部" clearable>
          <el-option label="全部" value="" />
          <el-option
            v-for="cat in categoryOptions"
            :key="cat"
            :label="cat"
            :value="cat"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品状态">
        <el-select v-model="filters.status" placeholder="全部" clearable>
          <el-option label="全部" value="" />
          <el-option label="启用" value="active" />
          <el-option label="禁用" value="inactive" />
          <el-option label="已删除" value="deleted" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch" :loading="loading">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
        <el-button type="success" @click="onCreate">新建商品</el-button>
      </el-form-item>
    </el-form>

    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedRows.length > 0">
      <el-button type="primary" @click="batchEnable">批量启用</el-button>
      <el-button type="warning" @click="batchDisable">批量禁用</el-button>
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
    </div>

    <!-- 商品表格 -->
    <el-table
      :data="products"
      border
      style="width: 100%"
      @selection-change="onSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="商品ID" width="120" />
      <el-table-column label="商品图片" width="100">
        <template #default="{ row }">
          <el-image
            :src="row.image"
            :preview-src-list="[row.image]"
            fit="cover"
            style="width: 60px; height: 60px; border-radius: 4px;"
          />
        </template>
      </el-table-column>
      <el-table-column prop="title" label="商品名称" min-width="200" />
      <el-table-column label="现价" width="100">
        <template #default="{ row }">
          <div style="color: #ff4d4f; font-weight: bold; font-size: 14px;">
            ¥{{ row.currentPrice }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="原价" width="100">
        <template #default="{ row }">
          <div style="color: #999; text-decoration: line-through; font-size: 14px;">
            ¥{{ row.originalPrice }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="80" />
      <el-table-column prop="sales" label="销量" width="80" />
      <el-table-column prop="category" label="分类" width="120" />
      <el-table-column label="活动标签" width="120">
        <template #default="{ row }">
          <el-tag
            v-for="activity in row.activity"
            :key="activity"
            :type="activity === '限时秒杀' ? 'danger' : activity === '特惠拼团' ? 'warning' : 'info'"
            size="small"
            style="margin-right: 4px;"
          >
            {{ activity }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag
            :type="row.status === 'active' ? 'success' : row.status === 'inactive' ? 'warning' : 'danger'"
          >
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="onEdit(row)">编辑</el-button>
          <el-button
            :type="row.status === 'active' ? 'warning' : 'success'"
            size="small"
            @click="toggleStatus(row)"
          >
            {{ row.status === 'active' ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" size="small" @click="onDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="onPageChange"
        @size-change="onSizeChange"
      />
    </div>

    <!-- 商品编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑商品' : '新建商品'"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="max-height: 500px; overflow-y: auto;"
      >
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-upload
              ref="uploadRef"
              :action="'http://localhost:3000/jjx/uploadimage'"
              :headers="{ 'Content-Type': 'multipart/form-data' }"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :on-error="handleImageError"
              :before-upload="beforeImageUpload"
              accept="image/*"
              style="display: inline-block;"
            >
              <el-button type="primary" :loading="imageUploading">
                {{ form.image ? '重新上传' : '上传图片' }}
              </el-button>
            </el-upload>
            <el-input 
              v-model="form.image" 
              placeholder="或直接输入图片URL" 
              style="flex: 1;"
            />
          </div>
          <div v-if="form.image" style="margin-top: 10px;">
            <img 
              :src="form.image.startsWith('http') ? form.image : `http://localhost:3000${form.image}`" 
              alt="商品图片" 
              style="max-width: 200px; max-height: 150px; border-radius: 4px; border: 1px solid #ddd;"
            />
          </div>
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类">
            <el-option
              v-for="cat in categoryOptions"
              :key="cat"
              :label="cat"
              :value="cat"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="现价" prop="currentPrice">
          <el-input-number v-model="form.currentPrice" :precision="2" :min="0" />
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input-number v-model="form.originalPrice" :precision="2" :min="0" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="form.stock" :min="0" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        <el-form-item label="规格单位" prop="unit">
          <el-input v-model="form.unit" placeholder="如：件、包、瓶等" />
        </el-form-item>
        <el-form-item label="活动标签">
          <el-checkbox-group v-model="form.activity">
            <el-checkbox label="限时秒杀">限时秒杀</el-checkbox>
            <el-checkbox label="特惠拼团">特惠拼团</el-checkbox>
            <el-checkbox label="热门">热门</el-checkbox>
            <el-checkbox label="推荐">推荐</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="商品标签">
          <el-select v-model="form.tags" multiple placeholder="请选择标签">
            <el-option label="新鲜直达" value="新鲜直达" />
            <el-option label="满减优惠" value="满减优惠" />
            <el-option label="品牌好货" value="品牌好货" />
            <el-option label="热销" value="热销" />
            <el-option label="好货上新" value="好货上新" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="submitLoading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";

// 响应式数据
const loading = ref(false);
const submitLoading = ref(false);
const imageUploading = ref(false);
const dialogVisible = ref(false);
const isEdit = ref(false);
const products = ref([]);
const selectedRows = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(20);

// 筛选条件
const filters = reactive({
  keyword: "",
  category: "",
  status: "",
});

// 表单数据
const form = reactive({
  id: "",
  title: "",
  image: "",
  category: "",
  currentPrice: 0,
  originalPrice: 0,
  stock: 0,
  sales: 0,
  description: "",
  unit: "",
  tags: [],
  activity: [],
  status: "active",
});

// 表单验证规则
const rules = {
  title: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  image: [{ required: true, message: "请上传或输入商品图片", trigger: "blur" }],
  category: [{ required: true, message: "请选择商品分类", trigger: "change" }],
  currentPrice: [{ required: true, message: "请输入现价", trigger: "blur" }],
  originalPrice: [{ required: true, message: "请输入原价", trigger: "blur" }],
  stock: [{ required: true, message: "请输入库存", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

// 分类选项
const categoryOptions = [
  "时令水果",
  "新鲜蔬菜", 
  "肉禽蛋类",
  "海鲜水产",
  "粮油调味",
  "乳品烘焙",
  "时令果蔬"
];

// 获取商品列表
const fetchProducts = async () => {
  try {
    loading.value = true;
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      keyword: filters.keyword,
      category: filters.category,
      status: filters.status,
    };
    
    const response = await axios.get('http://localhost:3000/jjx/getproducts', { params });
    
    if (response.data.code === 200) {
      products.value = response.data.data.list || [];
      total.value = response.data.data.total || 0;
    } else {
      ElMessage.error(response.data.msg || '获取商品列表失败');
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    ElMessage.error('获取商品列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const onSearch = () => {
  currentPage.value = 1;
  fetchProducts();
};

// 重置
const onReset = () => {
  Object.assign(filters, {
    keyword: "",
    category: "",
    status: "",
  });
  currentPage.value = 1;
  fetchProducts();
};

// 分页变化
const onPageChange = (page) => {
  currentPage.value = page;
  fetchProducts();
};

// 每页数量变化
const onSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchProducts();
};

// 选择变化
const onSelectionChange = (val) => {
  selectedRows.value = val;
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    active: '启用',
    inactive: '禁用',
    deleted: '已删除'
  };
  return statusMap[status] || status;
};

// 新建商品
const onCreate = () => {
  isEdit.value = false;
  dialogVisible.value = true;
};

// 编辑商品
const onEdit = (row) => {
  isEdit.value = true;
  Object.assign(form, row);
  dialogVisible.value = true;
};

// 切换状态
const toggleStatus = async (row) => {
  try {
    const newStatus = row.status === 'active' ? 'inactive' : 'active';
    const response = await axios.patch(`http://localhost:3000/jjx/updatestatus/${row.id}`, {
      status: newStatus
    });
    
    if (response.data.code === 200) {
      ElMessage.success('状态更新成功');
      fetchProducts();
    } else {
      ElMessage.error(response.data.msg || '状态更新失败');
    }
  } catch (error) {
    console.error('状态更新失败:', error);
    ElMessage.error('状态更新失败');
  }
};

// 删除商品
const onDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    const response = await axios.patch(`http://localhost:3000/jjx/updatestatus/${row.id}`, {
      status: 'deleted'
    });
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功');
      fetchProducts();
    } else {
      ElMessage.error(response.data.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 批量启用
const batchEnable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要启用的商品');
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确定要启用选中的 ${selectedRows.value.length} 个商品吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    const promises = selectedRows.value.map(row => 
      axios.patch(`http://localhost:3000/jjx/updatestatus/${row.id}`, { status: 'active' })
    );
    
    await Promise.all(promises);
    ElMessage.success('批量启用成功');
    fetchProducts();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量启用失败:', error);
      ElMessage.error('批量启用失败');
    }
  }
};

// 批量禁用
const batchDisable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要禁用的商品');
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确定要禁用选中的 ${selectedRows.value.length} 个商品吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    const promises = selectedRows.value.map(row => 
      axios.patch(`http://localhost:3000/jjx/updatestatus/${row.id}`, { status: 'inactive' })
    );
    
    await Promise.all(promises);
    ElMessage.success('批量禁用成功');
    fetchProducts();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量禁用失败:', error);
      ElMessage.error('批量禁用失败');
    }
  }
};

// 批量删除
const batchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的商品');
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个商品吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    const promises = selectedRows.value.map(row => 
      axios.patch(`http://localhost:3000/jjx/updatestatus/${row.id}`, { status: 'deleted' })
    );
    
    await Promise.all(promises);
    ElMessage.success('批量删除成功');
    fetchProducts();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
    }
  }
};

// 提交表单
const onSubmit = async () => {
  try {
    submitLoading.value = true;
    
    const formData = { ...form };
    
    if (isEdit.value) {
      // 更新商品
      const response = await axios.put(`http://localhost:3000/jjx/updateproduct/${formData.id}`, formData);
      if (response.data.code === 200) {
        ElMessage.success('商品更新成功');
        dialogVisible.value = false;
        fetchProducts();
      } else {
        ElMessage.error(response.data.msg || '商品更新失败');
      }
    } else {
      // 创建商品
      const response = await axios.post('http://localhost:3000/jjx/addproduct', formData);
      if (response.data.code === 200) {
        ElMessage.success('商品创建成功');
        dialogVisible.value = false;
        fetchProducts();
      } else {
        ElMessage.error(response.data.msg || '商品创建失败');
      }
    }
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败');
  } finally {
    submitLoading.value = false;
  }
};

// 图片上传前验证
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return false;
  }
  
  imageUploading.value = true;
  return true;
};

// 图片上传成功
const handleImageSuccess = (response) => {
  imageUploading.value = false;
  if (response.code === 200) {
    form.image = response.data.url;
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error(response.msg || '图片上传失败');
  }
};

// 图片上传失败
const handleImageError = (error) => {
  imageUploading.value = false;
  console.error('图片上传失败:', error);
  ElMessage.error('图片上传失败');
};

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: "",
    title: "",
    image: "",
    category: "",
    currentPrice: 0,
    originalPrice: 0,
    stock: 0,
    sales: 0,
    description: "",
    unit: "",
    tags: [],
    activity: [],
    status: "active",
  });
};

// 初始化
onMounted(() => {
  fetchProducts();
});
</script>

<style scoped>
.product-management {
  padding: 24px;
}

.filter-form {
  margin-bottom: 16px;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.batch-actions {
  margin-bottom: 16px;
  padding: 12px 20px;
  background: #f5f7fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
  background: #fff;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-table th) {
  background-color: #f5f7fa;
}

:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>